#include "mainwindow.h"
#include "ui_mainwindow.h"

#include <QDebug>

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    setWindowFlag(Qt::FramelessWindowHint);
//    setWindowOpacity(0.9);
    setAttribute(Qt::WA_TranslucentBackground);
    setAcceptDrops(true);

    btnClose = new QPushButton(this);
    btnClose->setStyleSheet("QPushButton{border-image:url(:img/close.png)}"
                            "QPushButton:hover{border-image:url(:img/close-hover.png)}");
    btnCode = new QPushButton(this);
    btnCode->setStyleSheet("QPushButton{border-image:url(:img/edit.png)}"
                            "QPushButton:hover{border-image:url(:img/edit-hover.png)}");
    btnMusic = new QPushButton(this);
    btnMusic->setStyleSheet("QPushButton{border-image:url(:img/volume.png)}"
                            "QPushButton:hover{border-image:url(:img/volume-hover.png)}");
    btnSetting = new QPushButton(this);
    btnSetting->setStyleSheet("QPushButton{border-image:url(:img/setting.png)}"
                               "QPushButton:hover{border-image:url(:img/setting-hover.png)}");
    toolBtn = new QToolButton(this);
    toolBtn->setStyleSheet("QToolButton{border-image:url(:img/tool.png);border-style:flat}"
                           "QToolButton:hover{border-image:url(:img/tool-hover.png);border-style:flat}");
    tool = new QMenu(this);
    action_1 = new QAction(this);
    action_2 = new QAction(this);
    action_3 = new QAction(this);
    action_4 = new QAction(this);
    action_5 = new QAction(this);

    for (int i = 1; i <= 16; i ++ )
    {
        btn[i] = new AppButton(this);
        btn[i]->setObjectName(tr("btn_%1").arg(i));
        btn[i]->hide();
    }

    init();

    qssFile = new QFile(":/stylesheet.qss", this);
    qssFile->open(QFile::ReadOnly);
    QString styleSheet = tr(qssFile->readAll());
    qApp->setStyleSheet(styleSheet);
    qssFile->close();

    connect(btnClose, &QPushButton::clicked, this, &MainWindow::closeWindow);
    connect(btnCode, &QPushButton::clicked, this, &MainWindow::codeWindow);
    connect(btnMusic, &QPushButton::clicked, this, &MainWindow::musicWindow);
    connect(btnSetting, &QPushButton::clicked, this, &MainWindow::settingWindow);
    connect(action_2, &QAction::triggered, this, &MainWindow::showFate);
    connect(action_3, &QAction::triggered, this, &MainWindow::starsWindow);
    connect(action_4, &QAction::triggered, this, &MainWindow::markWindow);
    connect(action_5, &QAction::triggered, this, &MainWindow::sufferWindow);

    for (int i = 1; i <= 16; i ++ )
    {
        connect(btn[i], &AppButton::clicked, this, &MainWindow::openApp);
        connect(btn[i], &AppButton::delBtn, this, &MainWindow::delApp);
    }
}
MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::init()
{
    QSettings openFile("usrInformation.ini", QSettings::IniFormat);
    openFile.setIniCodec(QTextCodec::codecForName("UTF-8"));
    backgroundPic = openFile.value("usr/backgroundPic").toString();
    WindowWidth = openFile.value("usr/WindowWidth").toInt();
    WindowHeight = openFile.value("usr/WindowHeight").toInt();
    windowFixed = openFile.value("usr/windowFixed").toInt();
    windowOnTop = openFile.value("usr/windowOnTop").toInt();
    windowBtnDisplay = openFile.value("usr/windowBtnDisplay").toInt();
    windowAppDisplay = openFile.value("usr/windowAppDisplay").toInt();
    transparentState = openFile.value("usr/windowOpacity").toInt();
    btnNum = openFile.value("usr/btnNum").toInt();

    //qDebug() << backgroundPic << WindowWidth << WindowHeight;

    btnSize = qMin(WindowWidth, WindowHeight) / 6 - 5;
    appSize = btnSize * 3 / 2;

    setFixedSize(WindowWidth, WindowHeight);
    btnInit();

    btnClose->resize(btnSize, btnSize);
    btnClose->move(width() - btnSize - 5, 5);
    btnCode->resize(btnSize, btnSize);
    btnCode->move(width() - btnSize - 5, 5 + (5 + btnSize));
    btnMusic->resize(btnSize, btnSize);
    btnMusic->move(width() - btnSize - 5, 5 + (5 + btnSize) * 2);
    btnSetting->resize(btnSize, btnSize);
    btnSetting->move(width() - btnSize - 5, 5 + (5 + btnSize) * 3);

    toolBtn->resize(btnSize, btnSize);
    toolBtn->move(width() - btnSize - 5, 5 + (5 + btnSize) * 4);
    action_1->setText(tr("聊天"));
    tool->addAction(action_1);
    action_2->setText(tr("今日运势"));
    tool->addAction(action_2);
    action_3->setText(tr("满天星河"));
    tool->addAction(action_3);
    action_4->setText(tr("便签"));
    tool->addAction(action_4);
    action_5->setText(tr("快乐游戏"));
    tool->addAction(action_5);
    toolBtn->setMenu(tool);
    toolBtn->setPopupMode(QToolButton::InstantPopup);

//    可以通过新写一个QWidget布局来使用layout，但这里因为我不需要放缩窗口，所以不麻烦了
//    rightLayout = new QVBoxLayout;
//    rightLayout->addWidget(btnClose);
//    rightLayout->addWidget(btnAbout);
//    rightLayout->setSpacing(5);
//    rightLayout->setContentsMargins(80, 5, 5, 0);
//    setLayout(rightLayout);

}

//      桌面图标
QPoint MainWindow::getBtnXY(int num)
{
    int col = (num - 1) % 4 + 1;
    int row = (num - 1) / 4 + 1;

    if (WindowHeight <= WindowWidth + 20)
        return QPoint((WindowWidth - 10 - 4 * appSize - btnSize) / 5 * col + appSize * (col - 1), (WindowHeight - 4 * appSize) / 5 * row + appSize * (row - 1));
    else
        return QPoint((WindowWidth - 10 - 4 * appSize - btnSize) / 5 * col + appSize * (col - 1), (WindowWidth - 4 * appSize) / 5 * row + appSize * (row - 1));
}
void MainWindow::btnInit()
{
    QSettings openFile("usrInformation.ini", QSettings::IniFormat);
    openFile.setIniCodec(QTextCodec::codecForName("UTF-8"));

    QString filename;
    QFileInfo file_info;
    QFileIconProvider icon_provider;
    QIcon icon;
    QStringList list;
    QStringList fullTitle;
    QString title;

    for (int i = 1; i <= btnNum; i ++ )
    {
        btn[i]->show();
        btn[i]->resize(appSize, appSize);
        btn[i]->move(getBtnXY(i));
        filename = openFile.value(tr("usr/btn_%1").arg(i)).toString();
        file_info = filename;
        icon = icon_provider.icon(file_info);
        btn[i]->setIcon(icon);
        btn[i]->setIconSize(iconSize());
        list = filename.split("/");
        fullTitle = list.at(list.length() - 1).split(".");
        title = fullTitle[0];
        btn[i]->setText(title);
        btn[i]->setToolButtonStyle(Qt::ToolButtonTextUnderIcon);
        btn[i]->setStyleSheet("QToolButton{background-color:transparent}");
    }
    for (int i = btnNum + 1; i <= 16; i ++ ) btn[i]->hide();

}
void MainWindow::openApp()
{
    AppButton *clickedButton = qobject_cast<AppButton *>(sender());
    QString btnName = clickedButton->objectName();
    QSettings openFile("usrInformation.ini", QSettings::IniFormat);
    openFile.setIniCodec(QTextCodec::codecForName("UTF-8"));
    QString filename = openFile.value(tr("usr/%1").arg(btnName)).toString();
    QDesktopServices::openUrl(QUrl("file:///" + filename));
}
void MainWindow::delApp()
{
    AppButton *clickedButton = qobject_cast<AppButton *>(sender());
    QString btnName = clickedButton->objectName();
    QSettings changeFile("usrInformation.ini", QSettings::IniFormat);
    changeFile.setIniCodec(QTextCodec::codecForName("UTF-8"));
    QString filename;
    quint16 i;

    for (i = btnName.at(btnName.length() - 1).unicode() - 48; i < btnNum; i ++ )
    {
        filename = changeFile.value(tr("usr/btn_%1").arg(i + 1)).toString();
        changeFile.setValue(tr("usr/btn_%1").arg(i), filename);
//        qDebug() << i;
    }
    btnNum -- ;
    changeFile.setValue(tr("usr/btnNum"), btnNum);
    changeFile.setValue(tr("usr/btn_%1").arg(i), "");

    btnInit();
}

//      设置桌面
void MainWindow::settingWindow()
{
    settings = new Settings(this);
//    settings->move(WindowWidth / 2, WindowHeight / 2);
    settings->setModal(true);
    connect(settings, &Settings::emitBackgroundPic, this, &MainWindow::setbackgroundpic);
    connect(settings, &Settings::emitSize, this, &MainWindow::setSize);
    connect(settings, &Settings::emitWindowFixed, this, &MainWindow::setWindowFixed);
    connect(settings, &Settings::emitWindowOnTop, this, &MainWindow::setWindowOnTop);
    connect(settings, &Settings::emitSetDefault, this, &MainWindow::setDefault);
    connect(settings, &Settings::emitBtnAndAppDisplay, this, &MainWindow::setWindowBtnAndAppDisplay);
    connect(settings, &Settings::emitOpacity, this, &MainWindow::setOpacity);
    settings->show();
}
void MainWindow::setbackgroundpic(bool changed, QString str)
{
//    backgroundNum = (backgroundNum + 1) % 4;
//    setStyleSheet(tr("MainWindow{border-image:url(%1)}").arg(gif[backgroundNum]));

    if (!changed)
    {
        backgroundPic = str;
        QSettings saveFile("usrInformation.ini", QSettings::IniFormat);
        saveFile.setIniCodec(QTextCodec::codecForName("UTF-8"));
        saveFile.setValue("usr/backgroundPic", backgroundPic);
    }
}
void MainWindow::setSize(int w, int h)
{
    WindowWidth = w;
    WindowHeight = h;
    QSettings saveFile("usrInformation.ini", QSettings::IniFormat);
    saveFile.setIniCodec(QTextCodec::codecForName("UTF-8"));
    saveFile.setValue("usr/WindowWidth", WindowWidth);
    saveFile.setValue("usr/WindowHeight", WindowHeight);

    if (WindowWidth == 1920 && WindowHeight == 1080)
    {
        setWindowState(Qt::WindowMaximized);
        windowFixed = 1;
        saveFile.setValue("usr/windowFixed", windowFixed);
    }
    else setFixedSize(WindowWidth, WindowHeight);

    init();
}
void MainWindow::setWindowFixed(bool checked)
{
    if (checked && !windowFixed)
    {
        windowFixed = 1 - windowFixed;
        QSettings saveFile("usrInformation.ini", QSettings::IniFormat);
        saveFile.setIniCodec(QTextCodec::codecForName("UTF-8"));
        saveFile.setValue("usr/windowFixed", windowFixed);
    }
    else if (!checked && windowFixed)
    {
        windowFixed = 1 - windowFixed;
        QSettings saveFile("usrInformation.ini", QSettings::IniFormat);
        saveFile.setIniCodec(QTextCodec::codecForName("UTF-8"));
        saveFile.setValue("usr/windowFixed", windowFixed);
    }
}
void MainWindow::setWindowOnTop(bool checked)
{
    if ((checked && !windowOnTop) || (!checked && windowOnTop))
    {
        windowOnTop = 1 - windowOnTop;
        QSettings saveFile("usrInformation.ini", QSettings::IniFormat);
        saveFile.setIniCodec(QTextCodec::codecForName("UTF-8"));
        saveFile.setValue("usr/windowOnTop", windowOnTop);
    }

    if (windowOnTop)
    {
        hide();
        setWindowFlags(Qt::WindowStaysOnTopHint | Qt::FramelessWindowHint);
        show();
    }
    else
    {
        setWindowFlags(this->windowFlags());
        setWindowFlags(Qt::FramelessWindowHint);
        show();
    }
}
void MainWindow::setWindowBtnAndAppDisplay(bool btnChecked, bool appChecked)
{
    if ((btnChecked && windowBtnDisplay) || (!btnChecked && !windowBtnDisplay))
    {
        windowBtnDisplay = 1 - windowBtnDisplay;
        QSettings saveFile("usrInformation.ini", QSettings::IniFormat);
        saveFile.setIniCodec(QTextCodec::codecForName("UTF-8"));
        saveFile.setValue("usr/windowBtnDisplay", windowBtnDisplay);
    }

    if ((appChecked && windowAppDisplay) || (!appChecked && !windowAppDisplay))
    {
        windowAppDisplay = 1 - windowAppDisplay;
        QSettings saveFile("usrInformation.ini", QSettings::IniFormat);
        saveFile.setIniCodec(QTextCodec::codecForName("UTF-8"));
        saveFile.setValue("usr/windowAppDisplay", windowAppDisplay);
    }
}
void MainWindow::setOpacity(int opacity)
{
    transparentState = opacity;
    QSettings saveFile("usrInformation.ini", QSettings::IniFormat);
    saveFile.setIniCodec(QTextCodec::codecForName("UTF-8"));
    saveFile.setValue("usr/windowOpacity", transparentState);
    update();
}
void MainWindow::setDefault()
{
    QSettings saveFile("usrInformation.ini", QSettings::IniFormat);
    saveFile.setIniCodec(QTextCodec::codecForName("UTF-8"));
    saveFile.setValue("usr/backgroundPic", "");
    saveFile.setValue("usr/WindowWidth", 576);
    saveFile.setValue("usr/WindowHeight", 324);
    saveFile.setValue("usr/windowFixed", 0);
    saveFile.setValue("usr/windowOnTop", 0);
    saveFile.setValue("usr/windowBtnDisplay", 0);
    saveFile.setValue("usr/windowAppDisplay", 1);
    saveFile.setValue("usr/windowOpacity", 255);

    init();
}

//      代码编辑器
void MainWindow::codeWindow()
{
    QMessageBox::warning(this, tr("施工中···"), tr("施工中···"), QMessageBox::Yes);
}

//      音乐播放器
void MainWindow::musicWindow()
{
    QMessageBox::warning(this, tr("施工中···"), tr("施工中···"), QMessageBox::Yes);
}

//      每日运势
void MainWindow::showFate()
{
    fate = new Fate(this);
    fate->show();
}

void MainWindow::starsWindow()
{
    stars = new Stars(this);
    stars->show();
}

void MainWindow::markWindow()
{
    mark = new Mark(this);
    mark->show();
}

void MainWindow::sufferWindow()
{
    suffer = new Suffer(this);
    suffer->show();
}

/**
 * 窗口的基本设置
 */

void MainWindow::closeWindow()
{
    exit(1);
}
void MainWindow::paintEvent(QPaintEvent *event)
{
    QPainter p(this);
    p.save();
    p.fillRect(this->rect(), QColor(230, 230, 230, tr("%1").arg(transparentState).toInt()));
    QPixmap pixmap(backgroundPic);
    p.drawPixmap(0, 0, width(), height(), pixmap);
    p.restore();
//    qDebug() << height() << width();
}
void MainWindow::enterEvent(QEvent *)
{
    btnClose->show();
    btnCode->show();
    btnMusic->show();
    btnSetting->show();
    toolBtn->show();

    for (int i = 1; i <= btnNum; i ++ )
    {
        btn[i]->show();
    }
}
void MainWindow::leaveEvent(QEvent *)
{
    if (!windowBtnDisplay)
    {
        btnClose->hide();
        btnCode->hide();
        btnMusic->hide();
        btnSetting->hide();
        toolBtn->hide();
    }

    if (!windowAppDisplay)
    {
        for (int i = 1; i <= btnNum; i ++ )
        {
            btn[i]->hide();
        }
    }
}
void MainWindow::dragEnterEvent(QDragEnterEvent *event)
{
    if (event->mimeData()->hasUrls())
        event->acceptProposedAction();
    else event->ignore();
}
void MainWindow::dropEvent(QDropEvent *event)
{
    event->ignore();
    const QMimeData *mimeData = event->mimeData();      // 获取MIME数据
    if (mimeData->hasUrls())                            // 如果数据中包含URL
    {
        QList<QUrl> urlList = mimeData->urls();         // 获取URL列表
        // 将其中第一个URL表示为本地文件路径
        fileName = urlList.at(0).toLocalFile();
        if (!fileName.isEmpty())                        // 如果文件路径不为空
        {
            if (btnNum < 16)
            {
                QSettings saveFile("usrInformation.ini", QSettings::IniFormat);
                saveFile.setIniCodec(QTextCodec::codecForName("UTF-8"));

                bool ok = true;
                for (int i = 1; i <= btnNum; i ++ )
                {
                    QString j = saveFile.value(tr("usr/btn_%1").arg(i)).toString();
                    if (j == fileName)
                    {
                        ok = false;
                        break;
                    }
                }

                if (ok)
                {
                    btnNum ++ ;
                    saveFile.setValue(tr("usr/btnNum"), btnNum);
                    saveFile.setValue(tr("usr/btn_%1").arg(btnNum), fileName);
                    btnInit();
                }
                else QMessageBox::warning(this, "警告", "文件已存在", QMessageBox::Yes);
            }
            else QMessageBox::warning(this, "警告", "装满啦", QMessageBox::Yes);
        }
    }
}
void MainWindow::mousePressEvent(QMouseEvent *event)
{
    if (event->button() == Qt::LeftButton && windowFixed == 0)
    {
        m_move = true;
        m_startPoint = event->globalPos();
        m_windowPoint = this->frameGeometry().topLeft();
    }
}
void MainWindow::mouseMoveEvent(QMouseEvent *event)
{
    if (m_move)
    {
//        QRect deskRect = QGuiApplication::primaryScreen()->geometry();
        QPoint relativePos = event->globalPos() - m_startPoint;
//        if (this->x() <= 0 && relativePos.x() < 0) relativePos.setX(-m_windowPoint.x());
//        if (this->y() <= 0 && relativePos.y() < 0) relativePos.setY(-m_windowPoint.y());
        this->move(m_windowPoint + relativePos);
    }
}
void MainWindow::mouseReleaseEvent(QMouseEvent *event)
{
    if (event->button() == Qt::LeftButton)
    {
        m_move = false;
    }
}
